package com.lyl.excel.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.lyl.excel.excel.Dept;
import com.lyl.excel.excel.Emp;
import com.lyl.excel.valid.ExcelResult;
import com.lyl.excel.valid.ExcelUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mr.Luo
 * @date 2022-09-27 17:22
 * @desc
 */
@RestController
public class TestExcelController {

    @GetMapping("/valid")
    public Object valid() {
        List<Emp> empList = ListUtil.toList(
                new Emp(1, "张三", 1, 18),
                new Emp(2, "", 1, 38),
                new Emp(3, "张三", 0, 15),
                new Emp(4, null, 1, 21)
        );
        ExcelResult<Emp> result = new ExcelResult<>();

        List<Emp> list = empList.stream()
                .filter(emp -> ExcelUtil.valid(emp, result))
                .collect(Collectors.toList());
        result.setReplaceCount(list.size());
        return result;
    }

    @GetMapping("/validDept")
    public Object validDept() {
        List<Dept> deptList = ListUtil.toList(
                new Dept(1, null, 1),
                new Dept(2, "张三", 1),
                new Dept(3, null, null)
        );
        ExcelResult<DeptError> result = new ExcelResult<>();
        deptList.forEach(dept -> {
            //ExcelUtil.valid(dept, result, (excelResult, s) -> excelResult.addErrorData(new DeptError(dept.getId(), s)));
        });
        return result;
    }

    @GetMapping("/validDept2")
    public Object validDept2() {
        List<Dept> deptList = ListUtil.toList(
                new Dept(1, null, 1),
                new Dept(2, "张三", 1),
                new Dept(3, null, null)
        );
        ExcelResult<DeptError> result = new ExcelResult<>();
        deptList.forEach(dept -> {
            ExcelUtil.valid(dept, constraintViolations -> {
                ConstraintViolation<Dept> first = CollUtil.getFirst(constraintViolations);
                result.addErrorData(new DeptError(dept.getId(),first.getMessage()));
            });
        });
        return result;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class DeptError {
        private Integer id;
        private String errMsg;
    }
}
